package com.powerunion.datacollection.service;

import java.util.Date;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.quartz.JobDetail;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.dao.TaskInfoDao;
import com.powerunion.datacollection.model.CollectionTaskVO;
import com.powerunion.datacollection.model.jsonObject.CollectionTaskJSONObject2;
import com.powerunion.datacollection.quartz.CronExpConversion;
import com.powerunion.datacollection.quartz.TaskScheduler;
import com.powerunion.datacollection.quartz.job.CollectionTask;
import com.powerunion.util.log.LogHelper;

public class TaskInfoManager {
	private static Logger logger = LogHelper.getInstance().getLogger(
			TaskInfoManager.class);
	private TaskInfoDao dao = null;

	public TaskInfoManager() {
		super();
		this.dao = (TaskInfoDao) DaoFactory.getInstance().getDao(
				TaskInfoDao.class);
	}

	public String save(String saveStr, String currentUser) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(saveStr)) {
			String[] args = { "saveStr" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter saveStr NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		// 参数为空
		if (StringUtils.isEmpty(currentUser)) {
			String[] args = { "currentUser" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter currentUser NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		JSONObject jsonObject = JSONObject.fromObject(saveStr);
		CollectionTaskJSONObject2 ctjo = (CollectionTaskJSONObject2) JSONObject
				.toBean(jsonObject, CollectionTaskJSONObject2.class);
		CollectionTaskVO ck = new CollectionTaskVO();

		// 复制属性值
		BeanUtils.copyProperties(ck, ctjo);
		
		String id = ck.getId();
		String resultId = "";
		if(!StringUtils.isEmpty(id)) {//修改任务
			int num = this.dao.getInstanceNum(id);
			if(num > 0){//已经存在任务实例，则不允许修改
				logger.debug("已经存在任务实例，不能修改！");
				return "";
			}else{
				//删除掉绑定的任务调度
				String taskName = id + "_task_instance";
				TaskScheduler.getInstance().deleteTask(taskName);
				resultId = this.saveTask(ck,currentUser);
			}
		}else{
			resultId = this.saveTask(ck,currentUser);
		}
		return resultId;
	}
	
	private String saveTask(CollectionTaskVO ck,String currentUser) throws Exception {
		ck.setCreateDate(new Date());

		ck.setCrtUserCode(currentUser);
		String exactlyTime = ck.getExactlyTime();
		ck.setExactlyTime(Format.getInstance().formatTime(exactlyTime));

		String resultId = this.dao.save(ck);
		if (!StringUtils.isEmpty(resultId)) {
			ck.setExactlyTime(exactlyTime);// 重新设置回页面的原始日期 比如：2010-3-17T12:30
											// PM
			int taskType = ck.getType();
			if (taskType == 0) {// 自动型
				int submitType = ck.getSubmitType();
				JobDetail jd = new JobDetail();
				jd.getJobDataMap().put("name", ck.getName());
				jd.getJobDataMap().put("description", ck.getDescription());
				jd.getJobDataMap().put("crtUserCode", ck.getCrtUserCode());
				jd.getJobDataMap().put("formId", ck.getFormId());
				jd.getJobDataMap().put("procId", ck.getProcId());
				jd.getJobDataMap().put("submitType",
						String.valueOf(ck.getSubmitType()));
				jd.getJobDataMap().put("periodsTime", ck.getPeriodsTime());
				jd.getJobDataMap().put("exactlyTime", ck.getExactlyTime());
				jd.getJobDataMap().put("periodsPreValue",
						ck.getPeriodsPreValue());
				jd.getJobDataMap().put("periodsLastValue",
						ck.getPeriodsLastValue());
				jd.getJobDataMap().put("id", resultId);

				String taskName = resultId + "_task_instance";

				if (submitType != 0) {
					// 具体时间格式类似 12:30 PM 或 12:30 AM
					String HMS = ck.getPeriodsLastValue().substring(0,
							ck.getPeriodsLastValue().length() - 3);
					String[] times = StringUtils.split(HMS, ":");
					if (times == null || times.length == 0) {// 没有设置的话
																// 初始化为早上10点
						times = new String[2];
						times[0] = "10";
						times[1] = "0";
					}
					String ap = ck.getPeriodsLastValue().substring(
							ck.getPeriodsLastValue().length() - 2,
							ck.getPeriodsLastValue().length());
					int hour = 0;
					if (ap.equals("PM")) {
						hour = Integer.parseInt(times[0]) + 12;
					} else {
						hour = Integer.parseInt(times[0]);
					}
					String minuteStr = times[1];
					int minute = Integer.parseInt(minuteStr);
					int day = Integer.parseInt(ck.getPeriodsPreValue());
					switch (submitType) {
					case Constants.TASK_PERIODS_TYPE_DAYLY:
						TaskScheduler.getInstance().scheduleDialy(
								CollectionTask.class, taskName, hour, minute,
								jd);
						break;
					case Constants.TASK_PERIODS_TYPE_WEEKLY:
						TaskScheduler.getInstance().scheduleWeekly(
								CollectionTask.class, taskName, day, hour,
								minute, jd);
						break;
					case Constants.TASK_PERIODS_TYPE_MONTHLY:
						TaskScheduler.getInstance().scheduleMonthly(
								CollectionTask.class, taskName, day, hour,
								minute, jd);
						break;
					}
				} else {
					// quartz时间表达式
					String cronExpression = CronExpConversion
							.convertDateToCronExp(ck.getExactlyTime());
					logger.debug("cronExpression:" + cronExpression);
					TaskScheduler.getInstance().schedule(CollectionTask.class,
							taskName, cronExpression, jd);
				}
			}
		}
		return resultId;
	}

	public boolean delete(String[] codes) throws Exception {
		// 参数为空
		if (codes.length < 1) {
			String[] args = { "codes" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter codes NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.delete(codes);
	}

	public CollectionTaskVO findByKey(String id)throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.getBykey(id);
	}

	public String getCollectionTasks(String categoryId, int start, int limit) {
		// 参数为空
		if (StringUtils.isEmpty(categoryId)) {
			String[] args = { "categoryId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter categoryId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		String results = this.dao.getCollectionTasks(categoryId, start, limit);

		return results;
	}
	
	public int getInstanceNum(String id) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getInstanceNum(id);
	}

}
